package com.wwcom.darteagle.fragment;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.wwcom.darteagle.R;
import com.wwcom.darteagle.data.DartEagleDatabase;
import com.wwcom.darteagle.model.MatchInfo;
import com.wwcom.darteagle.model.MatchPlayer;

public class PlayerHistoryMatchListFragment extends Fragment {
	public static final String PLAYER_NAME="playerName";
	private String playerName;
	private ListView playerMatchListView; 
	private PlayerMatchArrayAdapter playerMatchArrayAdapter;
	OnMatchSelectedListener mListener;
	
    // Container Activity must implement this interface
    public interface OnMatchSelectedListener {
        public void onMatchSelected(MatchInfo matchInfo);
    }
    
	/** Called when the fragment is first created. */	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) {
		     	
        View v= inflater.inflate(R.layout.playerhistory_select_match, container, false); 

        Bundle arguments= this.getArguments();
        playerName= arguments.getString(PLAYER_NAME);
        if (playerName == null) { 
        	playerName= savedInstanceState.getString(PLAYER_NAME);
        }

        //set page title
    	((TextView)v.findViewById(R.id.playerhistory_matchlist_title)).setText(
    			getString(R.string.playerhistory_select_match,playerName));        	        	
                        
        DartEagleDatabase db= new DartEagleDatabase(getActivity());
        List<MatchInfo> playerMatches= db.getPlayerMatchInfos(playerName);
        db.close();
        
        playerMatches.add(0, null); //add an empty item to the front of the list        
        playerMatchListView= (ListView) v.findViewById(R.id.playerhistory_matchlist);
        playerMatchArrayAdapter = new PlayerMatchArrayAdapter(getActivity(),playerMatches);
	    playerMatchListView.setAdapter(playerMatchArrayAdapter);    	    	
	    playerMatchListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				MatchInfo matchInfo= (MatchInfo)(playerMatchListView.getItemAtPosition(pos));	
		        mListener.onMatchSelected(matchInfo);
			}                 
	   });
                	   	  
       return v;                 
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnMatchSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnMatchSelectedListener");
        }
    }    
        
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
  	  savedInstanceState.putString(PLAYER_NAME,playerName);
    } 
    
	private class PlayerMatchArrayAdapter extends ArrayAdapter<MatchInfo> {
    	private final List<MatchInfo> list;
    	private final Context context;

    	public PlayerMatchArrayAdapter(Context context, List<MatchInfo> list) {
    		super(context, R.layout.playerhistory_matchlist_listentry, list);
    		this.context = context;
    		this.list = list;
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View view = null;
    		if (convertView == null) {
    			LayoutInflater inflator = ((Activity) context).getLayoutInflater();
    			view = inflator.inflate(R.layout.playerhistory_matchlist_listentry, null);    			
    		} else {
    			view = convertView;
    		}
    		TextView tv= (TextView)view.findViewById(R.id.playerhistory_matchlist_matchtitle);
    		MatchInfo mi= list.get(position);
    		if (mi != null) {
	    		Date date= new Date(mi.getDate());
	    		DateFormat dateFormatter;
	
	    		dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
	    		String matchTitle= dateFormatter.format(date)+": ";
	    		String[] playerNames= new String[mi.getMatchPlayers().size()];
	    		int pNo= 0;
	    		for (MatchPlayer mp : mi.getMatchPlayers()) {
	    			playerNames[pNo]= mp.getPlayer().getName();
	    			if (mi.getNumSets() > 0) {
	    				playerNames[pNo]+= " "+mp.getNumSets();
	    			} else {
	    				playerNames[pNo]+= " "+mp.getNumLegs();    				
	    			}
	    			pNo++;
	    		}
	    		matchTitle+= TextUtils.join(", ",playerNames);
		    	tv.setText(matchTitle);
		    	
	    		tv= (TextView)view.findViewById(R.id.playerhistory_matchlist_matchdescription);
		    	tv.setText(list.get(position).getMatchDescription());
		    	view.setTag(list.get(position));
    		} else {
		    	tv.setText(getString(R.string.playerhistory_overallstats_title,playerName));		    	
	    		tv= (TextView)view.findViewById(R.id.playerhistory_matchlist_matchdescription);
		    	tv.setText(getString(R.string.playerhistory_overallstats_description,playerName));
		    	view.setTag(null);    			
    			
    		}
    		return view;
    	}
    }
    
}